package com.wutianyi.classloader;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.wutianyi.task.Tasks;

public class MyClassLoader extends ClassLoader
{
    // basePath gives the path to which this class
    // loader appends "/<typename>.class" to get the
    // full path name of the class file to load

    byte[] classData = null;

    public MyClassLoader(byte[] classData)
    {
        this.classData = classData;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public synchronized Class loadClass(String className, boolean resolveIt) throws ClassNotFoundException
    {

        Class result;

        // Check the loaded class cache
        result = findLoadedClass(className);
        if (result != null)
        {
            // Return a cached class
            return result;
        }

        // Check with the system class loader
        try
        {
            result = super.findSystemClass(className);
            // Return a system class
            return result;
        }
        catch (ClassNotFoundException e)
        {
        }

        // Don't attempt to load a system file except through
        // the primordial class loader
        if (className.startsWith("java."))
        {
            throw new ClassNotFoundException();
        }

        // Try to load it from the basePath directory.
        if (classData == null)
        {
            System.out.println("GCL - Can't load class: " + className);
            throw new ClassNotFoundException();
        }

        // Parse it
        result = defineClass(className, classData, 0, classData.length);
        if (result == null)
        {
            System.out.println("GCL - Class format error: " + className);
            throw new ClassFormatError();
        }

        if (resolveIt)
        {
            resolveClass(result);
        }

        // Return class from basePath directory
        return result;
    }

    public static void main(String[] args) throws Exception
    {
        byte[] classData = FileUtils.readFileToByteArray(new File("TestTasks.class"));
        ClassLoader cl = new MyClassLoader(classData);
        Tasks task = (Tasks) cl.loadClass("com.wutianyi.task.TestTasks").newInstance();
        task.run();
    }
}
